package com.simple.piger.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.simple.piger.utils.PublicUtil;
import com.simple.piger.entity.CmsSysPermission;
import com.simple.piger.entity.CmsSysRolePermission;
import com.simple.piger.mapper.CmsSysPermissionMapper;
import com.simple.piger.mapper.CmsSysRolePermissionMapper;
import com.simple.piger.service.CmsSysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * 服务实现类
 * @Author  donghj
 * @Date    2017/11/20 19:31
 */
@Service
public class CmsSysPermissionServiceImpl extends ServiceImpl<CmsSysPermissionMapper, CmsSysPermission> implements CmsSysPermissionService {
    @Autowired
    private CmsSysRolePermissionMapper cmsSysRolePermissionMapper;

    @Override
    public JSONArray getSysAllRights(){
        // 获取系统所有的模块、菜单和按钮权限
        EntityWrapper<CmsSysPermission> ew_cmsSysPermission = new EntityWrapper<>();
        ew_cmsSysPermission.orderBy("sort", true);
        List<CmsSysPermission> cmsSysPermissions = this.selectList(ew_cmsSysPermission);
        // 递归成树形结构
        JSONArray jsonArray = JSONArray.parseArray(JSONObject.toJSONString(cmsSysPermissions));
        JSONArray treeJson = PublicUtil.recursion(jsonArray, 0, "id", "parentId");
        return treeJson;
    }

    @Override
    public JSONArray getUserRigthsById(String id) {
        // 获取用户关联角色所拥有的模块、菜单和按钮权限
        LinkedHashMap<String, Object> sel_cmsSysPermission = new LinkedHashMap<>();
        sel_cmsSysPermission.put("user_id", id);
        List<CmsSysPermission> cmsSysPermissions = cmsSysRolePermissionMapper.selSysUserPermissionList(sel_cmsSysPermission);
        // 递归成树形结构
        JSONArray jsonArray = JSONArray.parseArray(JSONObject.toJSONString(cmsSysPermissions));
        JSONArray treeJson = PublicUtil.recursion(jsonArray, 0, "id", "parentId");
        return treeJson;
    }

    @Override
    public JSONArray getRoleRigthsById(Integer id) {
        // 获取角色所拥有的模块、菜单和按钮权限
        LinkedHashMap<String, Object> sel_cmsSysRolePermission = new LinkedHashMap<>();
        sel_cmsSysRolePermission.put("role_id", id);
        List<CmsSysRolePermission> cmsSysPermissions = cmsSysRolePermissionMapper.selSysRolePermissionList(sel_cmsSysRolePermission);
        JSONArray jsonArray = JSONArray.parseArray(JSONObject.toJSONString(cmsSysPermissions));
        return jsonArray;
    }
}